<template>
  <view class="event-record-page">
    <u-navbar placeholder
              leftIcon="arrow-left"
              :title="$t('pages_user_event_event_msg_41c54a7f')"
              @leftClick="goBack" />
    
    <mescroll-body
      ref="mescrollRef"
      @init="mescrollInit"
      @down="downCallback"
      @up="upCallback"
      :down="downOption"
      :up="upOption"
      :height="`${systemInfo.windowHeight - systemInfo.statusBarHeight - 44}px`"
    >
      <!-- 空状态 -->
      <view v-if="dataList.length === 0 && !loading" class="empty-container">
        <image class="empty-icon" src="/static/images/empty.png" mode="aspectFit" />
        <text class="empty-text">暂无报名记录</text>
        <button class="empty-btn" @click="goToHome">去报名</button>
      </view>

      <!-- 记录列表 -->
      <view v-else class="event-list">
        <view 
          v-for="(item, index) in dataList" 
          :key="index" 
          class="event-item"
          @click="viewEventDetail(item)"
        >
          <!-- 取消按钮 -->
          <view class="cancel-button-wrapper" v-if="canCancelRegistration(item)">
            <button 
              class="cancel-btn-top" 
              @click.stop="cancelRegistration(item)"
              :disabled="item.cancelling"
            >
              {{ item.cancelling ? '取消中' : '取消' }}
            </button>
          </view>

          <!-- 赛事信息 -->
          <view class="event-info">
            <view class="event-title">{{ item.name || '赛事名称' }}</view>
            <view class="event-time">报名时间：{{ formatTime(item.createDate) }}</view>
            <view class="event-begin-time">开始时间：{{ formatTime(item.beginTime) }}</view>
            <view class="event-status" :class="item.status === 0 ? 'status-pending' : item.status === 1 ? 'status-confirmed' : item.status === 2 ? 'status-processing' : item.status === 3 ? 'status-completed' : item.status === 4 ? 'status-cancelled' : item.status === 5 ? 'status-refunded' : 'status-unknown'">{{ item.status === 0 ? this.$t('pages_user_event_detail_detail_msg_047109de') : item.status === 1 ? this.$t('pages_user_event_detail_detail_msg_4113e726') : item.status === 2 ? this.$t('pages_event_list_list_msg_fb852fc6') : item.status === 3 ? this.$t('pages_event_grades_grades_msg_fad5222c') : item.status === 4 ? this.$t('pages_user_event_detail_detail_msg_2111ccbb') : item.status === 5 ? this.$t('pages_user_event_detail_detail_msg_e85018b9') : this.$t('pages_album_album_msg_903b25f6') }}</view>
          </view>

          <!-- 报名费用 -->
          <view class="order-total">
            <text class="total-label">报名费用：</text>
            <text class="total-price">¥{{ item.money || 0 }}</text>
          </view>

          <!-- 支付状态 -->
          <view class="pay-status">
            <text class="pay-label">支付状态：</text>
            <text class="pay-text" :class="item.payStatus === 0 ? 'pay-unpaid' : item.payStatus === 1 ? 'pay-paid' : item.payStatus === 2 ? 'pay-failed' : item.payStatus === 3 ? 'pay-refunded' : 'pay-unknown'">{{ item.payStatus === 0 ? this.$t('pages_user_event_detail_detail_msg_608afd77') : item.payStatus === 1 ? this.$t('pages_event_grades_grades_msg_8d02a562') : item.payStatus === 2 ? this.$t('pages_user_event_detail_detail_msg_4548cc1f') : item.payStatus === 3 ? this.$t('pages_user_event_detail_detail_msg_e85018b9') : this.$t('pages_album_album_msg_903b25f6') }}</text>
          </view>
        </view>
      </view>
    </mescroll-body>
  </view>
</template>

<script>
import { mapState } from 'vuex'
import MescrollMixin from '@/uni_modules/mescroll-uni/components/mescroll-uni/mescroll-mixins.js'

export default {
  name: 'EventRecord',
  mixins: [MescrollMixin],
  computed: {
    ...mapState({
      systemInfo: (state) => state.app.systemInfo,
    }),
  },
  data() {
    return {
      dataList: [],
      loading: false,
      downOption: {
        auto: true,
      },
      upOption: {
        auto: false,
      },
    }
  },
  methods: {
    // 返回
    goBack() {
      uni.navigateBack();
    },

    // 去首页报名
    goToHome() {
      uni.switchTab({
        url: '/pages/index/index'
      });
    },

    // mescroll上拉回调
    async upCallback(page) {
      try {
        const params = {
          current: page.num,
          size: page.size
        };

        const result = await this.$api.event.getList(params);
        console.log('报名记录数据:', result);
        
        if (result) {
          // 如果是第一页，直接赋值；否则追加数据
          if (page.num == 1) {
            this.dataList = result;
          } else {
            this.dataList = this.dataList.concat(result);
          }
          
          // 结束加载，传入当前页的数据长度和总页数
          this.mescroll.endByPage(result.length, Math.ceil(result.total / page.size));
        } else {
          this.dataList = page.num == 1 ? [] : this.dataList;
          this.mescroll.endByPage(0, 0);
        }
      } catch (error) {
        console.error('加载报名记录失败:', error);
        uni.showToast({
          title: '加载失败，请重试',
          icon: 'none'
        });
        this.mescroll.endErr();
      }
    },

    // mescroll下拉回调
    downCallback(mescroll) {
      // 下拉刷新的回调，这里可以重置一些数据，比如重置页码
      this.upCallback({ num: 1, size: 10 });
    },

    // 查看详情
    viewEventDetail(item) {
      uni.navigateTo({
        url: `/pages/user/event/detail/detail?data=${encodeURIComponent(JSON.stringify(item))}`
      });
    },

    // 格式化时间
    formatTime(time) {
      if (!time) return '';
      const date = new Date(time);
      return `${date.getFullYear()}-${String(date.getMonth() + 1).padStart(2, '0')}-${String(date.getDate()).padStart(2, '0')} ${String(date.getHours()).padStart(2, '0')}:${String(date.getMinutes()).padStart(2, '0')}`;
    },

    // 获取状态文本
    getStatusText(status) {
      const statusMap = {
        0: this.$t('pages_user_event_detail_detail_msg_047109de'),
        1: this.$t('pages_user_event_detail_detail_msg_4113e726'), 
        2: this.$t('pages_event_list_list_msg_fb852fc6'),
        3: this.$t('pages_event_grades_grades_msg_fad5222c'),
        4: this.$t('pages_user_event_detail_detail_msg_2111ccbb'),
        5: this.$t('pages_user_event_detail_detail_msg_e85018b9')
      };
      return statusMap[status] || this.$t('pages_album_album_msg_903b25f6');
    },

    // 获取状态样式类
    getStatusClass(status) {
      const statusClassMap = {
        0: 'status-pending',
        1: 'status-confirmed',
        2: 'status-processing', 
        3: 'status-completed',
        4: 'status-cancelled',
        5: 'status-refunded'
      };
      return statusClassMap[status] || 'status-unknown';
    },

    // 获取支付状态文本
    getPayStatusText(payStatus) {
      const payStatusMap = {
        0: this.$t('pages_user_event_detail_detail_msg_608afd77'),
        1: this.$t('pages_event_grades_grades_msg_8d02a562'),
        2: this.$t('pages_user_event_detail_detail_msg_4548cc1f'),
        3: this.$t('pages_user_event_detail_detail_msg_e85018b9')
      };
      return payStatusMap[payStatus] || this.$t('pages_album_album_msg_903b25f6');
    },

    // 获取支付状态样式类
    getPayStatusClass(payStatus) {
      const payStatusClassMap = {
        0: 'pay-unpaid',
        1: 'pay-paid',
        2: 'pay-failed',
        3: 'pay-refunded'
      };
      return payStatusClassMap[payStatus] || 'pay-unknown';
    },

    // 判断是否可以取消报名
    canCancelRegistration(item) {
      // 只有待处理(0)和已确认(1)状态的报名可以取消
      // 且支付状态不是已退款(3)
      return (item.status === 0 || item.status === 1) && item.payStatus !== 3;
    },

    // 取消报名
    async cancelRegistration(item) {
      uni.showModal({
        title: this.$t('pages_user_event_detail_detail_msg_e8606af7'),
        content: `确定要取消报名"${item.name}"吗？`,
        success: async (res) => {
          if (res.confirm) {
            try {
              // 设置取消中状态
              this.$set(item, 'cancelling', true);
              
              // 调用取消报名接口
              await this.$api.event.cancel({ orderId: item.id });
              
              uni.showToast({
                title: this.$t('pages_user_event_detail_detail_msg_3cbf24cc'),
                icon: 'success'
              });

              // 刷新列表
              this.mescroll.resetUpScroll();
              
            } catch (error) {
              console.error('取消报名失败:', error);
              uni.showToast({
                title: '取消失败，请重试',
                icon: 'none'
              });
            } finally {
              // 重置取消中状态
              this.$set(item, 'cancelling', false);
            }
          }
        }
      });
    }
  }
}
</script>

<style scoped lang="scss">
.event-record-page {
  background: #f8f8f8;
  min-height: 100vh;
}

.empty-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 120rpx 40rpx;
  font-size: 28rpx;
  color: #666;
  
  .empty-icon {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 32rpx;
    opacity: 0.6;
  }
  
  .empty-text {
    margin-bottom: 48rpx;
    font-size: 30rpx;
    color: #999;
  }
  
  .empty-btn {
    background: #007aff;
    color: white;
    border: none;
    border-radius: 999rpx;
    padding: 12rpx 60rpx;
    font-size: 28rpx;
  }
}

.event-list {
  padding: 24rpx;
  
  .event-item {
    background: #fff;
    border-radius: 16rpx;
    padding: 32rpx;
    margin-bottom: 24rpx;
    box-shadow: 0 2px 8px rgba(0, 0, 0, 0.06);
    transition: transform 0.2s ease;
    position: relative;
    
    &:active {
      transform: scale(0.98);
    }
  }
}

.event-info {
  margin-bottom: 24rpx;
  padding-bottom: 24rpx;
  border-bottom: 1px solid #f0f0f0;
  
  .event-title {
    font-size: 32rpx;
    font-weight: 600;
    color: #333;
    margin-bottom: 12rpx;
  }
  
  .event-time,
  .event-begin-time {
    font-size: 26rpx;
    color: #666;
    margin-bottom: 12rpx;
  }
  
  .event-status {
    display: inline-block;
    padding: 8rpx 16rpx;
    border-radius: 20rpx;
    font-size: 22rpx;
    font-weight: 500;
    
    &.status-pending {
      background: #fff3e0;
      color: #f57c00;
    }
    
    &.status-confirmed {
      background: #e3f2fd;
      color: #1976d2;
    }
    
    &.status-processing {
      background: #f3e5f5;
      color: #7b1fa2;
    }
    
    &.status-completed {
      background: #e8f5e8;
      color: #388e3c;
    }
    
    &.status-cancelled,
    &.status-refunded {
      background: #ffebee;
      color: #d32f2f;
    }
    
    &.status-unknown {
      background: #f5f5f5;
      color: #666;
    }
  }
}

.product-list {
  margin-bottom: 24rpx;
  
  .product-title {
    font-size: 26rpx;
    color: #666;
    margin-bottom: 16rpx;
  }
  
  .products {
    .product-item {
      display: flex;
      align-items: flex-start;
      margin-bottom: 16rpx;
      
      &:last-child {
        margin-bottom: 0;
      }
    }
    
    .product-image {
      width: 80rpx;
      height: 80rpx;
      border-radius: 8rpx;
      margin-right: 16rpx;
      background: #f5f5f5;
    }
    
    .product-details {
      flex: 1;
      
      .product-name {
        font-size: 28rpx;
        color: #333;
        margin-bottom: 8rpx;
        line-height: 1.4;
      }
      
      .product-spec {
        font-size: 24rpx;
        color: #666;
        margin-bottom: 8rpx;
      }
      
      .product-price-qty {
        display: flex;
        justify-content: space-between;
        align-items: center;
        
        .product-price {
          font-size: 28rpx;
          color: #ff6b35;
          font-weight: 600;
        }
        
        .product-quantity {
          font-size: 24rpx;
          color: #666;
        }
      }
    }
  }
}

.order-total {
  display: flex;
  justify-content: space-between;
  align-items: center;
  // border-top: 1px solid #f0f0f0;
  margin-bottom: 16rpx;
  
  .total-label {
    font-size: 28rpx;
    color: #333;
  }
  
  .total-price {
    font-size: 32rpx;
    color: #ff6b35;
    font-weight: 600;
  }
}

.pay-status {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16rpx;
  
  .pay-label {
    font-size: 28rpx;
    color: #333;
  }
  
  .pay-text {
    font-size: 26rpx;
    padding: 6rpx 12rpx;
    border-radius: 12rpx;
    font-weight: 500;
    
    &.pay-unpaid {
      background: #fff3e0;
      color: #f57c00;
    }
    
    &.pay-paid {
      background: #e8f5e8;
      color: #388e3c;
    }
    
    &.pay-failed {
      background: #ffebee;
      color: #d32f2f;
    }
    
    &.pay-refunded {
      background: #f3e5f5;
      color: #7b1fa2;
    }
    
    &.pay-unknown {
      background: #f5f5f5;
      color: #666;
    }
  }
}

.cancel-button-wrapper {
  position: absolute;
  top: 16rpx;
  right: 16rpx;
  z-index: 10;
  
  .cancel-btn-top {
    background: transparent;
    color: #ff4757;
    border: 2rpx solid #ff4757;
    border-radius: 999rpx;
    padding: 0rpx 40rpx;
    font-size: 24rpx;
    font-weight: 500;
    transition: all 0.3s ease;
    
    &:active {
      transform: scale(0.95);
      background: #ff4757;
      color: white;
    }
    
    &[disabled] {
      border-color: #ccc;
      color: #ccc;
      opacity: 0.6;
      transform: none;
      
      &:active {
        background: transparent;
        color: #ccc;
      }
    }
  }
}
</style>